import 'dart:async';

import 'package:aio/aio.dart';
import 'package:aio/src/route/refresh/easyrefresh/easy_classical_footer.dart';
import 'package:aio/src/route/refresh/easyrefresh/easy_classical_header.dart';
import 'package:flutter/material.dart';
import 'package:app/generated/app_strings.dart';
import 'package:app/src/http/bean/wroks/contract_bean.dart';
import 'package:app/src/http/bean/wroks/search_bean.dart';
import 'package:app/src/http/bean/ywx_limit.dart';
import 'package:app/src/http/model/review_model.dart';
import 'package:app/src/manager/ywx_manager.dart';
import 'package:app/src/ui/app_ui.dart';
import 'package:app/src/ui/dialog/dailog.dart';
import 'package:app/src/ui/popuwindow/popuwindow_search.dart';
import 'package:app/src/ui/route/helper/route_helper.dart';
import 'package:app/src/ui/route/works/public/image/ui_image_upload.dart';
import 'package:app/src/ui/route/works/public/items/ui_card.dart';
import 'package:app/src/ui/route/works/public/review_submitted.dart';
import 'package:app/src/utils/image_path_utils.dart';
// import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:easy_refresh/easy_refresh.dart';

import '../../../../http/model/material_requisition_model.dart';
import '../../../../manager/audit_manager.dart';
import 'content_list.dart';

///审核列表
class ReviewList extends StatefulWidget {
  static bool windowRefresh = false; //判断是否刷新，防止window平台无法自动刷新。
  static setWindowRefresh() {
    if (PlatformUtils.isWindows()) {
      ReviewList.windowRefresh = true;
    } else {
      ReviewList.windowRefresh = false;
    }
  }

  ///审核类型
  YwxItem item;

  ///搜索条件
  SearchInfo searchInfo;

  ///是否刷新
  bool isRefresh = true;

  ReviewList(this.item, this.searchInfo, this.isRefresh);

  @override
  _ReviewListState createState() {
    return _ReviewListState();
  }
}

class _ReviewListState extends State<ReviewList> {
  _ReviewListPresenter presenter = _ReviewListPresenter();
  EasyRefreshController? _controller;

  @override
  void initState() {
    super.initState();
    _controller = EasyRefreshController(
      controlFinishRefresh: true,
      controlFinishLoad: true,
    );
    // print(
    //     '=====================================================================状态初始化');
    ReviewList.setWindowRefresh();
    windowRefresh();
  }

  ///window平台刷新
  windowRefresh() {
    if (ReviewList.windowRefresh) {
      ReviewList.windowRefresh = false;
      if (PlatformUtils.isWindows()) {
        presenter.searchInfo = widget.searchInfo;
        presenter.item = widget.item;
        presenter?.getContractdogetlist(context, 0, () {
          setState(() {
            //resetLoadState 刷新完成。
            // _controller?.resetLoadState();
            IndicatorResult result = IndicatorResult.success; //成功
            _controller?.finishRefresh(result,
                true); //第二个参数最好设置为true，不然会报错：If you want to modify the result, you can set force to true.
            _controller?.resetFooter();
          });
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    AuditManager.getAuditManager()
        .setDetailsWithAuto(false, "review_list.dart"); //fixme 不在审核详情页面。
    presenter._state = this;
    windowRefresh();
    // print(
    //     '=====================================================================视图构建${presenter.datas?.length}');
    presenter.searchInfo = widget.searchInfo;
    presenter.item = widget.item;
    if (widget.isRefresh) {
      AppUi.easyRefreshcallRefresh(_controller);
      widget.isRefresh = false;
    }
    return EasyRefresh(
      controller: _controller,
      // firstRefresh: true,
      refreshOnStart: true,
      header: EasyClassicalHeader(
        context,
        refreshText: AppStrings.of(context).refreshText,
        refreshReadyText: AppStrings.of(context).refreshReadyText,
        refreshingText: AppStrings.of(context).refreshingText,
        refreshedText: AppStrings.of(context).refreshedText,
        refreshFailedText: AppStrings.of(context).refreshFailedText,
      ),
      //footer 尾部，上拉加载更多布局
      footer: EasyClassicalFooter(
        context,
        loadText: AppStrings.of(context).loadText,
        loadReadyText: AppStrings.of(context).loadReadyText,
        loadingText: AppStrings.of(context).loadingText,
        loadedText: AppStrings.of(context).loadedText,
        loadFailedText: AppStrings.of(context).loadFailedText,
        noMoreText: AppStrings.of(context).noMoreText,
        infoText: AppStrings.of(context).infoText +
            '${DateTimeUtils.getDateTimeWithTime()}',
        showInfo: true,
      ),
      onRefresh: () async {
        if (mounted) {
          Completer<void> completer = new Completer();
          presenter?.getContractdogetlist(context, 0, () {
            completer.complete();
            if (mounted) {
              setState(() {
                //resetLoadState 刷新完成。
                // _controller?.resetLoadState();
                // var isNoMore = presenter.isNoMore();
                // _controller?.finishRefresh(success: true, noMore: isNoMore);
                IndicatorResult result = IndicatorResult.success; //成功
                //result=IndicatorResult.fail;//失败
                _controller?.finishRefresh(result,
                    true); //第二个参数最好设置为true，不然会报错：If you want to modify the result, you can set force to true.
                _controller?.resetFooter();
              });
            }
          });
          await completer.future;
        }
      },
      onLoad: () async {
        var isNoMore = presenter.isNoMore(); //提前判断是否有更多数据
        if (isNoMore) {
          //没有更多数据了
          if (mounted) {
            setState(() {
              // _controller?.finishLoad(success: true, noMore: isNoMore);
              IndicatorResult result = IndicatorResult.success; //加载成功
              if (isNoMore) {
                result = IndicatorResult.noMore; //没有更多数据了。
              }
              _controller?.finishLoad(result,
                  true);
            });
          }
        } else {
          //还有更多数据
          Completer<void> completer = new Completer();
          presenter?.getContractdogetlist(context, presenter.PageNo + 1, () {
            completer.complete();
            if (mounted) {
              setState(() {
                var isNoMore = presenter.isNoMore();
                // _controller?.finishLoad(success: true, noMore: isNoMore);
                IndicatorResult result = IndicatorResult.success; //加载成功
                if (isNoMore) {
                  result = IndicatorResult.noMore; //没有更多数据了。
                }
                _controller?.finishLoad(result,
                    true);
              });
            }
          });
          await completer.future;
        }
      },
      child: CustomScrollView(slivers: <Widget>[
        SliverList(
          delegate: SliverChildBuilderDelegate(
                (context, index) {
              return _item(context, index);
            },
            childCount: presenter.datas?.getSize() ?? 0,
          ),
        ),
      ]),
      //slivers 主布局
    );
  }

  Widget _item(BuildContext context, int index) {
    // 数据个数：0	下标：5
    // print("数据个数：${presenter.datas?.length}\t下标：$index");
    ContractCopyInfo data = presenter.datas.getData(index);
    List<ContractCopyInfo>? datas = presenter.datas.getDatas(index);
    List<Widget> children = [];
    //第一行
    var _str = " ${index + 1}";
    if (StringUtils.isNotEmpty(data.ReviewTypeName)) {
      _str = " ${index + 1}." + data.ReviewTypeName!;
    } else {
      _str = " ${AppStrings.of(context).TheSerial}：${index + 1}";
    }
    children.add(Row(
      children: [
        Image.asset(
          ImagePathUtils.getPathWithImageEntry("ic_entry.png"),
          width: 14,
        ),
        Listener(
          onPointerUp: (event) {
            if (StringUtils.isNotEmpty(data.ReviewTypeName)) {
              TextUtils.copyText(data.ReviewTypeName); //文本复制
            }
          },
          child: Text(
            _str, //ReviewTypeName
            style: AppStyle.textStyleWithEntryTitle(),
          ),
        ),
        Expanded(
          child: Text(''),
        ),
        Text(
          "  " + data.YwxName!,
          style: AppStyle.textStyleWithEntryBlue(),
        ),
      ],
    ));
    //中间内容
    children
        .add(ContentList.ywxItem(context, presenter.item, data, datas: datas));
    var ShenheName = data.getShenhe(context);
    if (presenter.item?.changerecord ?? false) {
      ShenheName = AppStrings.of(context).ToView; //查看;（提成比例审核里的更改记录，通通显示查看）
    }
    //最后一行
    var lastRowChildrens = <Widget>[];
    lastRowChildrens.add(Expanded(
      child: Text(''),
    ));
    lastRowChildrens.add(Text(
      "  " + data.getOrderOrStatusName()!,
      style: AppStyle.textStyleWithEntryTitle(),
    ));
    lastRowChildrens.add(AppUi.getSizeBox(width: 24));
    lastRowChildrens.add(MaterialButton(
      onPressed: () {
        Auditmaterial? material = null;
        if (widget.item.ReviewType == ReviewType.GetPurDemandList ||
            widget.item.ReviewType == ReviewType.GetPurDemandListMT02 ||
            widget.item.ReviewType == ReviewType.GetPurDemandListMT03) {
          ///fixme 请购单审核特定参数
          material = Auditmaterial();
          material?.IsApproval = widget.searchInfo.isApproval();
          material?.YwxName = data?.YwxName ?? "";
        }
        //详情跳转
        AppRouteHelper.goWorksDetails(context, widget.item, data,
                material: material)
            ?.then((value) {
          UiImageUpLoad.clear(); //图片清除
          //列表是否刷新：null	false
          // print(
          //     "===================================列表是否刷新：${value}\t$isRefreshPreviousAppList");
          if (value != null || isRefreshPreviousAppList) {
            isRefreshPreviousAppList = false;
            AppUi.easyRefreshcallRefresh(_controller); //重新刷新。
          }
        });
      },
      shape: RoundedRectangleBorder(
          side: BorderSide.merge(
              BorderSide(color: Colors.blueAccent, width: 1), BorderSide.none),
          borderRadius: BorderRadius.all(Radius.circular(20))),
      child: Text(
        ShenheName,
        style: AppStyle.textStyleWithEntryTitleBlue(),
      ),
    ));
    if (widget.searchInfo.isApproval() &&
        (widget.item.ReviewType == ReviewType.GetPurDemandList ||
            widget.item.ReviewType == ReviewType.GetPurOrder ||
            widget.item.ReviewType == ReviewType.GetPurContract ||
            widget.item.ReviewType == ReviewType.GetLogisticsContract) &&
        (data.StatusName?.contains("审核中") ?? false)) {
      //fixme 现在请购单审核,和采购单审核，采购合同审核，运输合同审核，只要查询条件为已审核，并且为审核中。都有撤回按钮
      // if (widget.searchInfo.isApproval() &&
      //     widget.item.ReviewType == ReviewType.GetPurDemandList &&
      //     data.recall) {
      ///请购单审核里的撤回按钮；已审核里的审核中，才有撤销按钮
      lastRowChildrens.add(AppUi.getSizeBox(width: 24));
      lastRowChildrens.add(MaterialButton(
        onPressed: () {
          presenter?.withdraw(context, data?.wfId, (isSuccess) {
            if (isSuccess) {
              if (mounted) {
                setState(() {
                  //resetLoadState 刷新完成。
                  //_controller?.resetLoadState();
                  // var isNoMore = presenter.isNoMore();
                  // _controller?.finishRefresh(success: true, noMore: isNoMore);
                  IndicatorResult result = IndicatorResult.success; //成功
                  //result=IndicatorResult.fail;//失败
                  _controller?.finishRefresh(result,
                      true); //第二个参数最好设置为true，不然会报错：If you want to modify the result, you can set force to true.
                  _controller?.resetFooter();
                });
              }
            }
          });
        },
        shape: RoundedRectangleBorder(
            side: BorderSide.merge(
                BorderSide(color: Colors.blueAccent, width: 1),
                BorderSide.none),
            borderRadius: BorderRadius.all(Radius.circular(20))),
        child: Text(
          AppStrings.of(context).withdraw,
          style: AppStyle.textStyleWithEntryTitleBlue(),
        ),
      ));
    }
    var lastRow = Row(
      children: lastRowChildrens,
    );
    children.add(Container(
      child: lastRow,
      height: 35,
      padding: EdgeInsets.zero,
      margin: EdgeInsets.zero,
    ));
    var column = Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: children,
    );
    return UiCard.build(context, column);
  }
}

class ReviewListDatas {
  List<ContractCopyInfo>? srcDatas = []; //服务器原始数据；
  List<List<ContractCopyInfo>>? listDatas = []; //归类整理后的数据。
  Map<String, List<ContractCopyInfo>> map = Map();

  ///原始数据大小
  int getSrcSize() {
    if (srcDatas != null && srcDatas!.length > 0) {
      return srcDatas!.length!;
    }
    return 0;
  }

  ///实际使用的数据大小
  int getSize() {
    ///list优先
    if (listDatas != null && listDatas!.length > 0) {
      return listDatas!.length!;
    }
    if (srcDatas != null && srcDatas!.length > 0) {
      return srcDatas!.length!;
    }
    return 0;
  }

  ///根据下标获取数据
  ContractCopyInfo getData(int index) {
    ContractCopyInfo data;
    if (listDatas != null && listDatas!.length > 0) {
      data = listDatas![index][0];
    } else {
      data = srcDatas![index];
    }
    return data;
  }

  ///根据下标获取数据
  List<ContractCopyInfo>? getDatas(int index) {
    if (listDatas != null && listDatas!.length > 0) {
      return listDatas![index];
    }
    return null;
  }

  clear() {
    srcDatas?.clear();
    listDatas?.clear();
    map?.clear();
  }
}

class _ReviewListPresenter {
  State? _state = null;

  bool mounted() {
    return _state?.mounted ?? false;
  }

  ///审核类型
  YwxItem? item = null;

  ///搜索条件
  SearchInfo? searchInfo = null;

  ///当前页码，从0开始
  int PageNo = 0;

  //服务器，总数据个数
  int TotalNum = 0;

  // List<ContractCopyInfo>? datas;
  ReviewListDatas datas = ReviewListDatas();

  ///判断是否没有更多数据了
  bool isNoMore() {
    if (datas != null && datas!.getSrcSize() > 0) {
      if (datas!.getSrcSize() >= TotalNum) {
        return true;
      }
    }
    return false;
  }

  ///获取待审核类型
  getContractdogetlist(
      BuildContext context, int PageNo, ResponseCallbackWithVoid response) {
    // print(
    //     '=====================================================================PageNo:$PageNo\t${isNoMore()}\tReviewType:$item ${item?.ReviewType}');
    if (!(searchInfo?.isOvertimeHours() ?? true)) {
      delayedWithMilliSeconds(500, () {
        response?.call();
        if (mounted()) {
          AppDialog.showDialogWithInfo(context,
              content: AppStrings.of(context)
                  .OvertimeHoursStart2Mes2); //搜索条件,开始时长不能大于结束时长!
        }
      });
      return;
    }
    ReviewModel.getContractdogetlist(context, false,
            ReviewType: item?.ReviewType,
            PageNo: PageNo.toString(),
            searchInfo: searchInfo)
        ?.then((value) {
      if (value == null) {
        if (mounted()) {
          // AppDialog.showDialogWithInfo(context,
          //     content: AppStrings.of(context).net_error_02); //服务器连接失败
          AppDialog.showDialogWithInfo(context,
              content: AppStrings.of(context).net_error_0); //网络连接失败
        }
      } else {
        if (value.isSuccessForCode()) {
          if (value.isSuccessForData()) {
            TotalNum = value.TotalNum;
            var newData = value.Data;
            if (PageNo == 0) {
              datas.srcDatas = value.Data;
              datas.map.clear();
            } else {
              datas.srcDatas?.addAll(value.Data!);
            }
            if (item?.ReviewType == ReviewType.GetPurOrder ||
                item?.ReviewType == ReviewType.GetPurOrderMT02 ||
                item?.ReviewType == ReviewType.GetPurOrderMT03) {
              ///采购单审核；数据要自己整理归类一下。
              datas?.listDatas?.clear();
              var map = datas.map;
              newData?.forEach((element) {
                if (element.PurOrderCode != null) {
                  if (map[element.PurOrderCode] == null) {
                    map[element.PurOrderCode!] = [];
                  }
                }
                map[element.PurOrderCode!]?.add(element);
              });
              map.forEach((key, value) {
                datas?.listDatas?.add(value);
              });
            }
            this.PageNo = PageNo;
            // print(
            //     '==============================================================个数：${datas?.length}\tTotalNum:${TotalNum}\tPageNo:$PageNo');
          } else {
            if (PageNo == 0) {
              datas?.clear();
            }
            if (PageNo == 0 || !isNoMore()) {
              //数据为空
              if (!isShowPopuMenuWithSearch) {
                if (mounted()) {
                  AppDialog.showDialogWithInfo(context,
                      content: AppStrings.of(context).dataEmpty);
                }
              }
            }
          }
        } else {
          if (!isShowPopuMenuWithSearch) {
            if (PageNo == 0) {
              datas?.clear();
            }
            if (mounted()) {
              AppDialog.showDialogWithInfo(context, content: value?.MsgDetail);
            }
          }
        }
      }
      response?.call();
    });
  }

  ///请购单审核，撤回
  withdraw(
      BuildContext context, String? wfId, ResponseCallbackWithBool response) {
    // print(
    //     '=====================================================================PageNo:$PageNo\t${isNoMore()}\tReviewType:$item ${item?.ReviewType}');
    MaterialModel.withdraw(context, false, wfId,
            PageNo: PageNo.toString(), searchInfo: searchInfo)
        ?.then((value) {
      bool isSuccess = false;
      if (value == null) {
        if (mounted()) {
          // AppDialog.showDialogWithInfo(context,
          //     content: AppStrings.of(context).net_error_02); //服务器连接失败
          AppDialog.showDialogWithInfo(context,
              content: AppStrings.of(context).net_error_0); //网络连接失败
        }
      } else {
        if (value.isSuccessForCode()) {
          isSuccess = true;
          Toast.showSuccess(
              AppStrings.of(context).withdrawsuccess, context); //撤回成功
        } else {
          if (!isShowPopuMenuWithSearch) {
            if (mounted()) {
              AppDialog.showDialogWithInfo(context, content: value?.MsgDetail);
            }
          }
        }
      }
      response?.call(isSuccess);
    });
  }
}
